package com.itheima.controller;




import com.itheima.pojo.Admin;
import com.itheima.pojo.Users;
import com.itheima.service.AdminService;
import com.itheima.service.UserService;
import com.itheima.vo.ErrorResult;
import com.itheima.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * 分页查询和查询用户详情信息
 */

@RestController
@RequestMapping("manage")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;

    /**
     * 分页查询
     * @param page
     * @param pagesize
     * @return
     */
    @PostMapping("users")
    public ResponseEntity<Object> findAll(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                          @RequestParam(value = "pagesize", defaultValue = "10") Integer pagesize,
                                          @RequestHeader(value = "Authorization") String token) throws IOException {
        Admin admin = this.adminService.queryUserByToken(token);
        if (null!=admin){
            PageResult pageResult = this.userService.findAll(page, pagesize);
            if(pageResult!=null) {
                return ResponseEntity.ok(pageResult);
            }
            ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("获取用户管理列表查询失败！").build();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        }
        ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("获取用户管理列表查询失败！").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }

    /**
     * 查询用户详情信息
     * @param Id
     * @return
     */

    @PostMapping("user")
    public ResponseEntity<Object> find(@RequestParam(value = "Id") Integer Id,
                                       @RequestHeader("Authorization") String token) throws IOException {
        Admin admin = this.adminService.queryUserByToken(token);
        if (null!=admin){
            Users users = this.userService.find(Id);
            if (users!=null) {
                return ResponseEntity.ok(users);
            }
            ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("获取用户详情信息失败！").build();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        }
        ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("获取用户详情信息失败！").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);



    }
}